package rpg002;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;

/**
 *
 * @author Smai
 *
 * Key binds
 * Moving
 * UP,DOWN,LEFT,RIGH (Arrow buttons)
 * K - Map Editor
 * J & L - Change current tile in Map Editor
 *
 */
public class Main {

  public static BufferedImage bImg;
  private int width = 1024;
  private int height = 640;
  private Canvas canvas;
  private MapEditor mapEditor;
  private Map map;
  private Game game;
  private ActionListener actionListener;
  private Player player;
  private UserInterface userInterface;
  private RightClickMenu rightClickMenu;
  private Magic magic;

  public Main() {
    actionListener = new ActionListener();
    mapEditor = new MapEditor();
    canvas = new Canvas();
    //Muista että kun muutat äijän aloitus kohtaa muuta myös törmäystarkistus
    //Peli tarkastaa vain pelaajan ympärillä vieressä olevat palikat.
    player = new Player(15, 9, 32, 32, "pelaaja", "Player", true, 250, 500);
    userInterface = new UserInterface(player, actionListener);
    map = new Map(player, actionListener, mapEditor, userInterface);
    game = new Game(actionListener, player, map, mapEditor);
    rightClickMenu = new RightClickMenu(actionListener,map);
    magic = new Magic(actionListener,map);

    //Viedään tietoja muista luokista
    actionListener.setActionListener(map, mapEditor, rightClickMenu);
    mapEditor.setMap(map, actionListener);

    JFrame frame = new JFrame();

    canvas.addKeyListener(actionListener);
    canvas.addMouseListener(actionListener);
    canvas.addMouseMotionListener(actionListener);

    canvas.setPreferredSize(new Dimension(width, height));

    frame.add(canvas);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    frame.setFocusable(false);
    frame.setLocation(400, 300);
    canvas.requestFocus();
  }

  public static void main(String[] args) {
    Main main = new Main();
    main.loop();
  }

  //Pelin silmukka
  public void loop() {

    bImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics gbi = bImg.createGraphics();

    while (true) {
      try {

        game.update();
        map.piirraKartta(gbi);
        player.paint(gbi);
        magic.paint(gbi);

        if (actionListener.buttonK) {
          mapEditor.paint(gbi);
        }
        userInterface.paint(gbi);

        if (actionListener.rmbClick) {
          rightClickMenu.paint(gbi);
        }
        canvas.repaint();

        Thread.sleep(33);
      } catch (Exception ex) {
        ex.printStackTrace();
        break;
      }
    }
  }
}
